package com.lqk.channel.socket.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class DatagramChannelDemo3 {
    //连接 read 和 write
    public static void main(String[] args) throws Exception {
        //打开DatagramChannel
        DatagramChannel connectChannel = DatagramChannel.open();
        //绑定
        connectChannel.bind(new InetSocketAddress(9999));

        //建立连接
        connectChannel.connect(new InetSocketAddress("127.0.0.1",9999));

        //write方法
        connectChannel.write(ByteBuffer.wrap("发送lqk".getBytes(StandardCharsets.UTF_8)));

        //read方法
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        while (true){
            readBuffer.clear();
            connectChannel.read(readBuffer);
            readBuffer.flip();
            System.out.println(Charset.forName("UTF-8").decode(readBuffer));
        }

    }
}
